<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>答题页</title>
    <link rel="icon" type="image/ico" href="pc/ico.png">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }
        .container {
            display: flex;
            padding: 20px;
            max-width: 1200px;
            margin: auto;
            gap: 20px;
        }
        .questions-container {
            flex: 3;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            max-height: 85vh;
            overflow-y: auto;
        }
        .question {
            margin-bottom: 20px;
        }
        .question h3 {
            margin-bottom: 10px;
        }
        .answers label {
            display: block;
            margin-bottom: 10px;
            cursor: pointer;
        }
        .feedback {
            font-size: 14px;
            margin-top: 10px;
            color: #007bff;
        }
        .answer-card {
            flex: 1;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            text-align: center;
            position: sticky;
            top: 20px;
            height: fit-content;
        }
        .answer-card .timer {
            font-size: 18px;
            margin-bottom: 20px;
        }
        .submit-btn {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 15px;
            cursor: pointer;
            font-size: 16px;
            border-radius: 8px;
            transition: background-color 0.3s;
            margin-top: 20px;
        }
        .submit-btn:hover {
            background-color: #0056b3;
        }
        .answer-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
            margin-bottom: 20px;
        }
        .answer-grid button {
            padding: 10px;
            cursor: pointer;
            border: 1px solid #ccc;
            border-radius: 4px;
            background-color: #f0f0f0;
            transition: background-color 0.3s;
        }
        .answer-grid button.selected {
            background-color: #007bff;
            color: white;
        }
        /* 手机端适配 */
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
                padding: 10px;
            }
            .questions-container {
                max-height: none;
                width: 100%;
                padding: 15px;
            }
            .question h3 {
                font-size: 18px;
            }
            .answer-card {
                position: relative;
                top: auto;
                width: 100%;
                margin-top: 10px;
            }
            .timer {
                font-size: 16px;
            }
            .answer-grid {
                grid-template-columns: repeat(5, 1fr); /* 改为五列以适应手机宽度 */
            }
            .submit-btn {
                font-size: 14px;
                padding: 10px;
            }
            .answers label {
                font-size: 14px;
            }
        }
        /* 超小屏幕（窄手机）适配 */
        @media (max-width: 480px) {
            .answer-grid {
                grid-template-columns: repeat(4, 1fr); /* 改为四列 */
            }
            .question h3 {
                font-size: 16px;
            }
            .submit-btn {
                font-size: 14px;
                padding: 8px;
            }
            .timer {
                font-size: 14px;
            }
        }
    </style>
</head>
<body>
<div class="nav-container" style="padding: 20px; text-align: left; max-width: 1200px; margin: auto;">
    <button class="submit-btn" onclick="goToHomePage()">返回首页</button>
</div>
<div class="container">
    <!-- Questions Container -->
    <div class="questions-container" id="questions-container">
        <!-- Question Blocks -->
    </div>

    <!-- Answer Card -->
    <div class="answer-card">
        <div class="timer" id="timer">01:40:00</div>
        <div class="answer-grid" id="answer-grid"></div>
    </div>
</div>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        const urlParams = new URLSearchParams(window.location.search);
        const subjectId = urlParams.get('subjectId');

        if (subjectId) {
            fetch(`/api/v1/questions/fetch?subjectId=${encodeURIComponent(subjectId)}&limit=10`)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        populateQuestions(data.data);
                    } else {
                        alert('获取题目失败，请重试。');
                    }
                })
                .catch(error => {
                    console.error('获取题目时出错:', error);
                    alert('获取题目时发生错误。');
                });
        } else {
            alert('未选择科目，返回首页。');
            window.location.href = '/';
        }
    });

    function populateQuestions(questions) {
        const questionsContainer = document.getElementById('questions-container');
        const answerGrid = document.getElementById('answer-grid');

        questionsContainer.innerHTML = '';
        answerGrid.innerHTML = '';

        questions.forEach((question, index) => {
            const inputType = question.isMultipleChoice ? 'checkbox' : 'radio';
            let questionHTML = `<div class="question" id="question-${index + 1}">
                <h3>${index + 1}. ${question.questionText}</h3>
                <div class="answers">`;

            question.options.forEach(option => {
                if (option.optionText.trim() !== "") {
                    questionHTML += `
                    <label>
                        <input type="${inputType}" name="question${index + 1}" value="${option.optionLabel}" data-question-id="${question.questionId}">
                        ${option.optionLabel}. ${option.optionText}
                    </label>
                `;
                }
            });

            questionHTML += `</div></div>`;
            questionsContainer.innerHTML += questionHTML;

            const button = document.createElement("button");
            button.textContent = index + 1;
            button.onclick = () => scrollToQuestion(index + 1);
            answerGrid.appendChild(button);
        });

        questionsContainer.innerHTML += `<button class="submit-btn" onclick="submitExam()">提交</button>`;
    }

    function scrollToQuestion(questionNumber) {
        const questionElement = document.getElementById(`question-${questionNumber}`);
        if (questionElement) {
            questionElement.scrollIntoView({ behavior: 'smooth' });
        }
    }

    function goToHomePage() {
        window.location.href = '/';
    }

    function submitExam() {
        const answers = [];
        const subjectId = parseInt(new URLSearchParams(window.location.search).get('subjectId'), 10);
        const questions = document.querySelectorAll('.question');

        questions.forEach((questionDiv, index) => {
            const questionId = questionDiv.querySelector('input[type="radio"], input[type="checkbox"]').dataset.questionId;
            const selectedOptions = questionDiv.querySelectorAll(`input[name="question${index + 1}"]:checked`);

            const userAnswers = Array.from(selectedOptions).map(option => option.value).join('');
            if (userAnswers) {
                answers.push({
                    questionId: parseInt(questionId, 10),
                    userAnswer: userAnswers,
                    subjectId: subjectId
                });
            }
        });

        fetch('/api/v1/questions/submit', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(answers)
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    showSubmissionResult(data.data);
                } else {
                    alert('提交答案失败，请重试。');
                }
            })
            .catch(error => {
                console.error('提交答案时出错:', error);
                alert('提交答案时发生错误。');
            });
    }

    function showSubmissionResult(results) {
        results.forEach(result => {
            const questionElement = document.querySelector(`[data-question-id="${result.questionId}"]`).closest('.question');
            const existingFeedback = questionElement.querySelector('.feedback');
            if (existingFeedback) existingFeedback.remove();

            const resultMessage = document.createElement('div');
            resultMessage.className = 'feedback';
            resultMessage.textContent = result.correct ? "答案正确" : `答案错误，正确答案是：${result.correctAnswer}`;
            resultMessage.style.color = result.correct ? 'green' : 'red';
            questionElement.appendChild(resultMessage);

            questionElement.style.border = result.correct ? '2px solid green' : '2px solid red';
            setTimeout(() => { questionElement.style.border = 'none'; }, 3000);
        });
    }
</script>
</body>
</html>
